package net.sf.midollo.io.lcdui.textbox;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;

public class TextBoxOutputStream extends OutputStream {

  protected final TextBox textBox;

  public TextBoxOutputStream(TextBox textBox) {
    this.textBox = textBox;
    this.textBox.setConstraints(this.textBox.getConstraints() | TextField.UNEDITABLE);
  }

  public void write(byte[] b, int off, int len) throws IOException {
    writeToTextBox(new String(b, off, len));
  }

  public void write(byte[] b) throws IOException {
    writeToTextBox(new String(b, 0, b.length));
  }

  public void write(int c) throws IOException {
    writeToTextBox(String.valueOf(c));
  }

  protected void writeToTextBox(String str) {
    synchronized (this.textBox) {
      int sizeOld = this.textBox.size();
      int strLen = str.length();
      int sizeNew = sizeOld + strLen;
      int sizeMax = this.textBox.getMaxSize();

      if (sizeNew > sizeMax) {
        if (strLen > sizeMax) {
          str = str.substring(strLen - sizeMax);
          strLen = sizeOld;
        }
        this.textBox.delete(0, strLen);
        sizeOld = this.textBox.size();
      }

      this.textBox.insert(str, sizeOld);
    }
  }
}
